from django.shortcuts import redirect
from django.contrib import messages
from django.contrib.auth import logout
from models import UserProfile, UserProfileForm
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
import logging
from django.template import RequestContext

def try_get_profile(request):
	try:
		profile = request.user.get_profile()
	except:
		profile = UserProfile(user=request.user)
	return profile

def render_to(template_name):
	def renderer(func):
		def wrapper(request, *args, **kw):
			output = func(request, *args, **kw)
			if not isinstance(output, dict):
				return output
			return render_to_response(template_name, output, context_instance=RequestContext(request))
		return wrapper
	return renderer


def logout_action(request):
	messages.success(request, 'You are logout.')
	logout(request)
	return redirect('/accounts/login')

@login_required(login_url='/accounts/login/')
@render_to('profile-form.html')
def profile_edit_action(request):
	profile = try_get_profile(request)
	if request.POST:
		form = UserProfileForm(request.POST, instance=profile)
		if form.is_valid():
			messages.success(request, 'Your changes saved successfuly.')
			form.save()
			redirect('/accounts/profile/view')
		pass
	else:
		form = UserProfileForm(instance =profile)
	
	return { 'form': form }

@login_required(login_url='/accounts/login/')
@render_to('profile.html')
def profile_view_action(request):
	profile = try_get_profile(request)
	return {'profile': profile}
